<script setup>
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCookieStore } from '@/stores/cookieStore'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute()
const router = useRouter()
const cookieStore = useCookieStore()
const emit = defineEmits(['uploadEnd'])

const uploadInput = ref(null)

onMounted(() => {
  // 上传歌曲
  uploadInput.value.addEventListener('change', watchUploadFn)
})

// 弹出框
const dialogVisible = ref(false)

// 正在上传歌曲的进度信息
const uploadProgressIofo = ref([])
const watchUploadFn = async function () {
  // 歌曲的上传进度信息
  uploadProgressIofo.value = [...this.files].map(item => {
    return {
      name: item.name,
      progress: '等待中'
    }
  })
  dialogVisible.value = true
  for (const file of this.files) {
    let formData = new FormData()
    formData.append('songFile', file)
    await request({
      method: 'POST',
      url: `/cloud?${Date.now()}&cookie=${cookieStore.cookie.cookie}`,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      data: formData,
      // 上传进度
      onUploadProgress: function (progressEvent) {
        const complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
        const index = uploadProgressIofo.value.findIndex(item => item.name === file.name)
        uploadProgressIofo.value[index].progress = complete
        // 上传完成，将歌曲信息从上传列表中清除
        if (complete === '100%') {
          ElMessage({
            type: 'success',
            message: uploadProgressIofo.value[index].name + '上传成功'
          })
          uploadProgressIofo.value.splice(index, 1)
        }
      }
    })
      .then(res => {
        const { data } = res
        // 上传完成，更新上传列表
        if (data.code === 200) {
          emit('uploadEnd', data.privateCloud.simpleSong)
        }
      })
      .catch(err => {
        ElMessage('上传出现错误')
        console.log(err);
      })
  }
}

// 点击上传歌曲前，进行登录状态判断
const handleUpload = (e) => {
  if (!cookieStore.cookie.cookie) {
    ElMessageBox.confirm(
      '上传歌曲前，请保持登录状态。立即去登录?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        router.push({
          path: '/login',
          query: {
            redirect: route.fullPath
          }
        })
      })
    e.preventDefault()
  }
}

onBeforeUnmount(() => {
  uploadInput.value.removeEventListener('change', watchUploadFn)
})

</script>

<template>
  <div class="cloud-disk-upload">
    <div class="upload-icon">
      <div class="cloud-icon">
        <i class="iconfont icon-cloudUpload"></i>
      </div>
      <input type="file" multiple class="upload-input" ref="uploadInput"
        :title="cookieStore.cookie.cookie ? '上传歌曲' : '上传歌曲前，请先登录账号'" @click="handleUpload">
    </div>

    <div class="upload-icon open-list" title="查看上传列表" @click="dialogVisible = true">
      <i class="iconfont icon-liebiaoxingshi"></i>
      <div class="upload-list-text">
      </div>
    </div>
    <el-dialog v-model="dialogVisible" width="900" title="歌曲上传列表">
      <li v-for="(item, index) in uploadProgressIofo" :key="index">
        <div class="info">
          <span>{{ item.name }}</span>
          <span>{{ item.progress }}</span>
        </div>
        <div class="progress-box">
          <div class="progress" :style="{ width: item.progress }"></div>
        </div>
      </li>
      <h3 v-if="!uploadProgressIofo.length > 0">上传列表为空</h3>
    </el-dialog>
  </div>
</template>

<style scoped lang='scss'>
.cloud-disk-upload {
  .upload-icon {
    position: fixed;
    bottom: 200px;
    right: 60px;
    width: 70px;
    height: 70px;
    border-radius: 50%;
    background-color: rgb(255, 255, 255);
    box-shadow: 0px 4px 10px #c0c0c0;

    .cloud-icon {
      width: 70px;
      height: 70px;
      display: flex;
      justify-content: center;
      align-items: center;

      .icon-cloudUpload {
        font-size: 27px;
      }

    }

    .upload-input {
      position: absolute;
      z-index: 100;
      top: 0;
      left: 0;
      height: 90px;
      width: 90px;
      opacity: 0;
      cursor: pointer;
    }
  }

  .open-list {
    right: 60px;
    bottom: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;

    .icon-liebiaoxingshi {
      font-size: 27px;
    }

  }

  li {
    margin-bottom: 20px;
    font-size: 16px;
  }

  h3 {
    line-height: 60px;
    text-align: center;
  }

  .info {
    display: flex;
    justify-content: space-between;
    padding: 10px 2px;
  }

  .progress-box {
    height: 5px;
    width: 100%;
    background-color: #dedede;
    overflow: hidden;
    border-radius: 4px;

    .progress {
      height: 5px;
      background-color: $sucColor;
      border-radius: 5px;
      width: 0%;
    }
  }
}

:deep(.el-overlay) {
  background-image: none !important;
  background-color: rgba(239, 239, 239, 0.3) !important;
}
</style>
